#include "cardgroup.h"
CardGroup::CardGroup(QWidget *parent)
    : QWidget(parent),
    m_lastPathRect(-1, -1, -1, -1)  // 初始化无效矩形
{
    m_flowLayout = new FlowLayout(this);
    m_flowLayout->setContentsMargins(5, 5, 5, 5);
    m_flowLayout->setAnimationEnabled(true);
    setAttribute(Qt::WA_TranslucentBackground);
    setStyleSheet("border: none;");
    // 初始化默认值
    m_borderRadius = 25;
    m_borderColor = QColor(200, 200, 200);
    m_borderWidth = 1;
    m_backgroundColor = Qt::transparent;
}
CardGroup::~CardGroup()
{
    // 优化：避免重复删除，FlowLayout是QObject会随父对象自动销毁
}
void CardGroup::addCardView(CardView* cardView)
{
    m_flowLayout->addWidget(cardView);
    m_cardMap.insert(cardView->getDesBelow(),  cardView);
}
CardView* CardGroup::getCardView(const QString &str)
{
    return m_cardMap.value(str);
}
// 优化：添加属性变更检查
void CardGroup::setBorderRadius(int radius)
{
    if (m_borderRadius == radius) return;
    m_borderRadius = radius;
    updatePainterPath();
    update();
}
void CardGroup::setBorderColor(const QColor &color)
{
    if (m_borderColor == color) return;
    m_borderColor = color;
    update();  // 颜色变化不需要更新路径
}
void CardGroup::setBorderWidth(int width)
{
    if (m_borderWidth == width) return;
    m_borderWidth = width;
    updatePainterPath();
    update();
}
void CardGroup::setBackgroundColor(const QColor &color)
{
    if (m_backgroundColor == color) return;
    m_backgroundColor = color;
    update();  // 颜色变化不需要更新路径
}
// 新增：路径更新方法
void CardGroup::updatePainterPath()
{
    if (rect() != m_lastPathRect) {
        m_cachedPath = QPainterPath();
        const qreal halfPen = m_borderWidth / 2.0;
        QRectF drawRect = rect().adjusted(halfPen, halfPen, -halfPen, -halfPen);
        m_cachedPath.addRoundedRect(drawRect,  m_borderRadius, m_borderRadius);
        m_lastPathRect = rect();
    }
}
// 新增：处理大小变化事件
void CardGroup::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    updatePainterPath();  // 大小变化时更新路径
}
// 优化后的绘制方法
void CardGroup::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);

    // 当属性变化时更新路径
    if (m_cachedPath.isEmpty()  || rect() != m_lastPathRect) {
        updatePainterPath();
    }
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing,  m_borderRadius > 0);

    // 优化：使用缓存路径绘制
    painter.fillPath(m_cachedPath,  m_backgroundColor);

    // 优化：只在有边框时绘制边框
    if (m_borderWidth > 0) {
        painter.strokePath(m_cachedPath,  QPen(m_borderColor, m_borderWidth));
    }
}
